package com.jse.api;

import java.net.http.HttpClient.Version;
import java.net.http.HttpResponse;
import java.nio.file.Path;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.jse.Fs;
import com.jse.Http;
import com.jse.Jse;
import com.jse.json.JsonObject;
import com.jse.json.XML;

public class Oss {
	
	/**
	 * {@code
	 * 		Map.of("bucket","iepsy","path","www/2.jpg","file","d:/1.jpg","key","alikey","secret","alisecret")
	 * }
	 * 
	 * @param bucket "ali.oss.bucket" 上传的桶
	 * @param path www/3.pdf 上传的路径
	 * @param file d:/1.pdf 本地文件路径
	 * @param key 阿里key
	 * @param secret 阿里secret
	 * @return 
	 * @throws Exception
	 */
	public static String upload(Map<String,Object> map) {
		String bucket=map.containsKey("bucket")?map.get("bucket").toString()
				:Jse.conf.getString("ali.oss.bucket");
		String file=map.get("file").toString();
		var f=Path.of(file);
		String path=map.containsKey("path")?map.get("path").toString():"upload/"+f.getFileName().toString();
		String accessKeyId =map.containsKey("key")?map.get("key").toString()
				:Jse.conf.getString("ali.key");
		String accessKeySecret =map.containsKey("secret")?map.get("secret").toString()
				:Jse.conf.getString("ali.secret");
		String domain =map.containsKey("domain")?map.get("domain").toString()
				:Jse.conf.getString("ali.oss.domain");;
		String url="http://"+domain+"/"+path;
		Map<String,String> header=new HashMap<String, String>();
		String ds=Ali.toGMTString(new Date());//new Date().toGMTString();
		header.put("Date",ds);
		byte[] body=Fs.readAllBytes(f);
		String suffix=Fs.suffix(file);
		String contentType=Fs.mimeType(suffix,"");
		header.put("Content-Type", contentType);
		String str= "PUT\n\n"+contentType+"\n"+ds+"\n/"+bucket+"/"+path;
		String Authorization = "OSS "+accessKeyId+":";
		String sign = Ali.hmacSHA1Signature(accessKeySecret,str);
		header.put("Authorization", Authorization+sign);
		try {
			return Http.send(Version.HTTP_1_1,"PUT",url,body,60000,header,false,null).toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public static JsonObject list(Map<String,Object> map) {
		String bucket=map.containsKey("bucket")?map.get("bucket").toString()
				:Jse.conf.getString("ali.oss.bucket");
		String accessKeyId =map.containsKey("key")?map.get("key").toString()
				:Jse.conf.getString("ali.key");
		String accessKeySecret =map.containsKey("secret")?map.get("secret").toString()
				:Jse.conf.getString("ali.secret");
		String path =map.containsKey("path")?map.get("path").toString():"";
		String domain =map.containsKey("domain")?map.get("domain").toString()
				:Jse.conf.getString("ali.oss.domain");;
		String url="http://"+domain+"/"+path;
		Map<String,String> header=new HashMap<String, String>();
		String ds=Ali.toGMTString(new Date());//"Fri, 03 Feb 2023 07:25:18 GMT ";//;//new Date().toGMTString();
		header.put("Date",ds);
		String contentType="";//application/json
		header.put("Content-Type", contentType);
		String str= "GET\n\n"+contentType+"\n"+ds+"\n/"+bucket+"/"+"";
		String Authorization = "OSS "+accessKeyId+":";
		String sign = Ali.hmacSHA1Signature(accessKeySecret,str);
		header.put("Authorization", Authorization+sign);
		try {
			Object o=Http.send(Version.HTTP_1_1,"GET",url,"",60000,header,false,"");
			if(o instanceof HttpResponse<?> resp) {
				return XML.toJSONObject(resp.body().toString());
			}
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * path 删除 /结尾为文件夹 必须为空文件夹
	 * @param map
	 * @return
	 */
	public static String del(Map<String,Object> map) {
		String bucket=map.containsKey("bucket")?map.get("bucket").toString()
				:Jse.conf.getString("ali.oss.bucket");
		String accessKeyId =map.containsKey("key")?map.get("key").toString()
				:Jse.conf.getString("ali.key");
		String accessKeySecret =map.containsKey("secret")?map.get("secret").toString()
				:Jse.conf.getString("ali.secret");
		String path =map.containsKey("path")?map.get("path").toString():"";
		String domain =map.containsKey("domain")?map.get("domain").toString()
				:Jse.conf.getString("ali.oss.domain");;
		String url="http://"+domain+"/"+path;
		Map<String,String> header=new HashMap<String, String>();
		String ds=Ali.toGMTString(new Date());//new Date().toGMTString();
		header.put("Date",ds);
		String contentType="";
		header.put("Content-Type", contentType);
		String str= "DELETE\n\n"+contentType+"\n"+ds+"\n/"+bucket+"/"+path;
		String Authorization = "OSS "+accessKeyId+":";
		String sign = Ali.hmacSHA1Signature(accessKeySecret,str);//(AccessKeySecret,
		header.put("Authorization", Authorization+sign);
		try {
			Object o=Http.send(Version.HTTP_1_1,"DELETE",url,"",60000,header,false,"");
			return o.toString();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	
	
	public static void main(String[] args) {
		//, "LTAI8MDgUrXvLBpl" LTAI5tRBosa9HfpWeJkiQ7hx WZG5rWdvmfG73UHXhXiM8ONWbbthbv
		//OlEapJaG8KtKjqqPpLadX2b3zQ3p94
		String a=upload(Map.of("bucket","iepsy","path","upload/1.txt","file","d:/1.txt",
//				"key","LTAI5tAngJPSCz2auTjunjCu","secret","JefNK1lLu86ih4nDpnXiJiT556Opr1",
				"key","LTAI8MDgUrXvLBpl","secret","OlEapJaG8KtKjqqPpLadX2b3zQ3p94",
				"domain","iepsy.oss-cn-beijing.aliyuncs.com"));
		// Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
//		JsonObject a=list(Map.of("bucket","iepsy","path","?list-type=2&max-keys=1000",
////				"key","LTAI5tFHXhV8qhvNk3FmwYo6","secret","pDT71I3FD05XsDiVPTiDskC8IPL126",
//				"key","LTAI8MDgUrXvLBpl","secret","OlEapJaG8KtKjqqPpLadX2b3zQ3p94",
//				"domain","iepsy.oss-cn-beijing.aliyuncs.com"));
//		System.out.println(a.getJSONObject("ListBucketResult").get("CommonPrefixes").getClass().getName());
//		System.out.println(a.getJSONObject("ListBucketResult").get("Contents").getClass().getName());
//		String a=del(Map.of("bucket","iepsy","path","upload/2.txt",
//				"key","LTAI8MDgUrXvLBpl","secret","OlEapJaG8KtKjqqPpLadX2b3zQ3p94"
//				,"domain","iepsy.oss-cn-beijing.aliyuncs.com"));
//		String a=del(Map.of("bucket","xinjiaoyu","path","upload/8.txt",
//				"key","LTAI8MDgUrXvLBpl","secret","OlEapJaG8KtKjqqPpLadX2b3zQ3p94"
//				,"domain","xinjiaoyu.oss-cn-beijing.aliyuncs.com"));
		System.out.println(a);
	}
}
